<?php
namespace app\api\server;

use app\api\model\BaseConfig as BaseConfigModel;
use think\worker\Server;
use Workerman\Lib\Timer;
use app\admin\model\Member as MemberModel;
use think\facade\Db;
use app\common\common;

class Worker extends Server
{

    //protected $socket = 'websocket://localhost:2345';
    protected $socket = 'websocket://0.0.0.0:28792';
    //protected $socket = 'websocket://0.0.0.0:18791';
    //protected $socket = 'websocket://0.0.0.0:18792';

    protected static $heartbeat_time    =   55;

    public function onWorkerStart($worker)
    {
        Timer::add(1, function()use($worker)
        {
            $worker->count = 4;

            $time_now = time();

            $entrustData['buy'] = Db::name('member_entrust')->field('sum(num) as num,money,sum(already_num) as already_num')->where('entrust_state',1)->where('transaction_state',1)->group('money')->order('money desc')->limit(6)->select()->toArray();

            $entrustData['sell'] = Db::name('member_entrust')->field('sum(num) as num,money,sum(already_num) as already_num')->where('entrust_state',1)->where('transaction_state',2)->group('money')->order('money asc')->limit(6)->select()->toArray();

            $entrustData['adc_transaction'] = sprintf("%.4f",BaseConfigModel::config_data('adc_transaction'));

            usort($entrustData['sell'], function ($current, $next)
            {
                return $current['money'] < $next['money'];
            });


            foreach ($entrustData['sell'] as $k=>$v)
            {
                if($v['already_num'])   $entrustData['sell'][$k]['num'] = bcsub($v['num'],$v['already_num'],4);
            }

            foreach ($entrustData['buy'] as $k=>$v)
            {
                if($v['already_num'])   $entrustData['buy'][$k]['num'] = bcsub($v['num'],$v['already_num'],4);
            }
            /*if(count($entrustData['sell']) < 5)
            {
                for ($r = count($entrustData['sell']); $r < 5 ;$r++)
                {
                    $entrustData['sell'][$r]['num'] = $this->randFloat(1,100);
                    $entrustData['sell'][$r]['money'] = bcadd($entrustData['adc_transaction'],bcmul($entrustData['adc_transaction'],$this->randFloat(0.01,0.1),4),4);
                }

                usort($entrustData['sell'], function ($current, $next)
                {
                    return $current['money'] < $next['money'];
                });
            }

            //数据转换
            foreach ($entrustData['sell'] as $k=>$v)
            {

                $entrustData['sell'][$k]['num'] = ($v['num'] > 1000) ? number_format(floatval($v['num']),4) : bcadd($v['num'],$this->randFloat(1,100),4);

                $entrustData['sell'][$k]['money'] = ($v['money'] > 1000) ? number_format(floatval($v['money']),4) : number_format(floatval($v['money']),4);
            }*/

         /*   if(count($entrustData['buy']) < 5)
            {
                for ($r = count($entrustData['buy']); $r < 5 ;$r++)
                {
                    $entrustData['buy'][$r]['num'] = $this->randFloat(1,100);
                    $entrustData['buy'][$r]['money'] = bcsub($entrustData['adc_transaction'],bcmul($entrustData['adc_transaction'],$this->randFloat(0.01,0.1),4),4);
                }

                usort($entrustData['buy'], function ($current, $next)
                {
                    return $current['money'] < $next['money'];
                });
            }

            //数据转换
            foreach ($entrustData['buy'] as $k=>$v)
            {

                $entrustData['buy'][$k]['num'] = ($v['num'] > 1000) ? number_format(floatval($v['num']),4) : bcadd($v['num'],$this->randFloat(1,100),4);

                $entrustData['buy'][$k]['money'] = ($v['money'] > 1000) ? number_format(floatval($v['money']),4) : number_format(floatval($v['money']),4);
            }*/

            foreach ($worker->connections as $connection)
            {
               /* if (empty($connection->lastMessageTime)) {
                    $connection->lastMessageTime = $time_now;
                }

                if ($time_now - $connection->lastMessageTime > self::$heartbeat_time) {
                    $connection->close();
                }*/

                $connection->send(json_encode($entrustData));

            }
        });
    }


    /**

     * 生成0~1随机小数

     * @param Int $min

     * @param Int $max

     * @return Float

     */

    function randFloat($min=0, $max=1){

        return number_format($min + mt_rand()/mt_getrandmax() * ($max-$min),2);

    }
    public function onMessage($connection, $data)
    {
        /*if($data)
        {
            $member = MemberModel::address($data);

            //查看是否有新的充值或提现订单，有就推送给所有用户
            Timer::add(1, function () use ($connection, $member) {
                if ($member) {

                    $data = Db::name('member_entrust')->where(['mid' => $member->id, 'entrust_state' => 1])->order('create_time desc')->select();

                } else {
                    $data = [];
                }
                $connection->send(json_encode($data));
            });
        }*/
    }

    /**
     * 当连接建立时触发的回调函数
     * @param $connection
     */
    public function onConnect($connection)
    {
        $connection->send("连接成功");
    }

    /**
     * 当连接断开时触发的回调函数
     * @param $connection
     */
    public function onClose($connection)
    {

    }

    /**
     * 当客户端的连接上发生错误时触发
     * @param $connection
     * @param $code
     * @param $msg
     */
    public function onError($connection, $code, $msg)
    {
        echo "error $code $msg\n";
    }


}